<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>pgmpy.factors.discrete.CPD &#8212; pgmpy 0.1.2 documentation</title>
    
    <link rel="stylesheet" href="../../../../_static/sphinxdoc.css" type="text/css" />
    <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../../../',
        VERSION:     '0.1.2',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true,
        SOURCELINK_SUFFIX: '.txt'
      };
    </script>
    <script type="text/javascript" src="../../../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../../../_static/doctools.js"></script>
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" /> 
  </head>
  <body role="document">
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../../../../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../../../../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="nav-item nav-item-0"><a href="../../../../index.html">pgmpy 0.1.2 documentation</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="../../../index.html" accesskey="U">Module code</a> &#187;</li> 
      </ul>
    </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
            <p class="logo"><a href="../../../../index.html">
              <img class="logo" src="../../../../_static/logo.png" alt="Logo"/>
            </a></p>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <form class="search" action="../../../../search.html" method="get">
      <div><input type="text" name="q" /></div>
      <div><input type="submit" value="Go" /></div>
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <h1>Source code for pgmpy.factors.discrete.CPD</h1><div class="highlight"><pre>
<span></span><span class="ch">#!/usr/bin/env python3</span>
<span class="sd">&quot;&quot;&quot;Contains the different formats of CPDs used in PGM&quot;&quot;&quot;</span>
<span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">division</span>

<span class="kn">from</span> <span class="nn">itertools</span> <span class="k">import</span> <span class="n">product</span>
<span class="kn">from</span> <span class="nn">warnings</span> <span class="k">import</span> <span class="n">warn</span>
<span class="kn">import</span> <span class="nn">numbers</span>

<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>

<span class="kn">from</span> <span class="nn">pgmpy.factors.discrete</span> <span class="k">import</span> <span class="n">DiscreteFactor</span>
<span class="kn">from</span> <span class="nn">pgmpy.extern</span> <span class="k">import</span> <span class="n">tabulate</span>
<span class="kn">from</span> <span class="nn">pgmpy.extern</span> <span class="k">import</span> <span class="n">six</span>
<span class="kn">from</span> <span class="nn">pgmpy.extern.six.moves</span> <span class="k">import</span> <span class="nb">range</span><span class="p">,</span> <span class="nb">zip</span>
<span class="kn">from</span> <span class="nn">pgmpy.utils</span> <span class="k">import</span> <span class="n">StateNameInit</span>
<span class="kn">from</span> <span class="nn">pgmpy.utils</span> <span class="k">import</span> <span class="n">StateNameDecorator</span>


<div class="viewcode-block" id="TabularCPD"><a class="viewcode-back" href="../../../../factors.html#pgmpy.factors.discrete.CPD.TabularCPD">[docs]</a><span class="k">class</span> <span class="nc">TabularCPD</span><span class="p">(</span><span class="n">DiscreteFactor</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Defines the conditional probability distribution table (cpd table)</span>

<span class="sd">    Examples</span>
<span class="sd">    --------</span>
<span class="sd">    For a distribution of P(grade|diff, intel)</span>

<span class="sd">    +-------+--------------------+------------------+</span>
<span class="sd">    |diff   |      easy          |    hard          |</span>
<span class="sd">    +-------+-----+------+-------+------+----+------+</span>
<span class="sd">    |intel  |dumb |  avg | smart | dumb |avg |smart |</span>
<span class="sd">    +-------+-----+------+-------+------+----+------+</span>
<span class="sd">    |gradeA |0.1  |  0.1 |  0.1  | 0.1  |0.1 | 0.1  |</span>
<span class="sd">    +-------+-----+------+-------+------+----+------+</span>
<span class="sd">    |gradeB |0.1  |  0.1 |  0.1  | 0.1  |0.1 | 0.1  |</span>
<span class="sd">    +-------+-----+------+-------+------+----+------+</span>
<span class="sd">    |gradeC |0.8  |  0.8 |  0.8  | 0.8  |0.8 | 0.8  |</span>
<span class="sd">    +-------+-----+------+-------+------+----+------+</span>

<span class="sd">    values should be</span>
<span class="sd">    [[0.1,0.1,0.1,0.1,0.1,0.1],</span>
<span class="sd">    [0.1,0.1,0.1,0.1,0.1,0.1],</span>
<span class="sd">    [0.8,0.8,0.8,0.8,0.8,0.8]]</span>

<span class="sd">    &gt;&gt;&gt; cpd = TabularCPD(&#39;grade&#39;,3,[[0.1,0.1,0.1,0.1,0.1,0.1],</span>
<span class="sd">                                    [0.1,0.1,0.1,0.1,0.1,0.1],</span>
<span class="sd">                                    [0.8,0.8,0.8,0.8,0.8,0.8]],</span>
<span class="sd">                                    evidence=[&#39;diff&#39;, &#39;intel&#39;], evidence_card=[2,3])</span>
<span class="sd">    &gt;&gt;&gt; print(cpd)</span>
<span class="sd">    +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">    | diff    | diff_0  | diff_0  | diff_0  | diff_1  | diff_1  | diff_1  |</span>
<span class="sd">    +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">    | intel   | intel_0 | intel_1 | intel_2 | intel_0 | intel_1 | intel_2 |</span>
<span class="sd">    +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">    | grade_0 | 0.1     | 0.1     | 0.1     | 0.1     | 0.1     | 0.1     |</span>
<span class="sd">    +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">    | grade_1 | 0.1     | 0.1     | 0.1     | 0.1     | 0.1     | 0.1     |</span>
<span class="sd">    +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">    | grade_2 | 0.8     | 0.8     | 0.8     | 0.8     | 0.8     | 0.8     |</span>
<span class="sd">    +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">    &gt;&gt;&gt; cpd.values</span>
<span class="sd">    array([[[ 0.1,  0.1,  0.1],</span>
<span class="sd">            [ 0.1,  0.1,  0.1]],</span>

<span class="sd">           [[ 0.1,  0.1,  0.1],</span>
<span class="sd">            [ 0.1,  0.1,  0.1]],</span>

<span class="sd">           [[ 0.8,  0.8,  0.8],</span>
<span class="sd">            [ 0.8,  0.8,  0.8]]])</span>
<span class="sd">    &gt;&gt;&gt; cpd.variables</span>
<span class="sd">    [&#39;grade&#39;, &#39;diff&#39;, &#39;intel&#39;]</span>
<span class="sd">    &gt;&gt;&gt; cpd.cardinality</span>
<span class="sd">    array([3, 2, 3])</span>
<span class="sd">    &gt;&gt;&gt; cpd.variable</span>
<span class="sd">    &#39;grade&#39;</span>
<span class="sd">    &gt;&gt;&gt; cpd.variable_card</span>
<span class="sd">    3</span>

<span class="sd">    Parameters</span>
<span class="sd">    ----------</span>
<span class="sd">    variable: int, string (any hashable python object)</span>
<span class="sd">        The variable whose CPD is defined.</span>

<span class="sd">    variable_card: integer</span>
<span class="sd">        cardinality of variable</span>

<span class="sd">    values: 2d array, 2d list or 2d tuple</span>
<span class="sd">        values of the cpd table</span>

<span class="sd">    evidence: array-like</span>
<span class="sd">        evidences(if any) w.r.t. which cpd is defined</span>

<span class="sd">    evidence_card: integer, array-like</span>
<span class="sd">        cardinality of evidences (if any)</span>

<span class="sd">    Public Methods</span>
<span class="sd">    --------------</span>
<span class="sd">    get_values()</span>
<span class="sd">    marginalize([variables_list])</span>
<span class="sd">    normalize()</span>
<span class="sd">    reduce([values_list])</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="nd">@StateNameInit</span><span class="p">()</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">variable</span><span class="p">,</span> <span class="n">variable_card</span><span class="p">,</span> <span class="n">values</span><span class="p">,</span>
                 <span class="n">evidence</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">evidence_card</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">variable</span> <span class="o">=</span> <span class="n">variable</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">variable_card</span> <span class="o">=</span> <span class="kc">None</span>

        <span class="n">variables</span> <span class="o">=</span> <span class="p">[</span><span class="n">variable</span><span class="p">]</span>

        <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">variable_card</span><span class="p">,</span> <span class="n">numbers</span><span class="o">.</span><span class="n">Integral</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s2">&quot;Event cardinality must be an integer&quot;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">variable_card</span> <span class="o">=</span> <span class="n">variable_card</span>

        <span class="n">cardinality</span> <span class="o">=</span> <span class="p">[</span><span class="n">variable_card</span><span class="p">]</span>
        <span class="k">if</span> <span class="n">evidence_card</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">evidence_card</span><span class="p">,</span> <span class="n">numbers</span><span class="o">.</span><span class="n">Real</span><span class="p">):</span>
                <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s2">&quot;Evidence card must be a list of numbers&quot;</span><span class="p">)</span>
            <span class="n">cardinality</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">evidence_card</span><span class="p">)</span>

        <span class="k">if</span> <span class="n">evidence</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">evidence</span><span class="p">,</span> <span class="n">six</span><span class="o">.</span><span class="n">string_types</span><span class="p">):</span>
                <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s2">&quot;Evidence must be list, tuple or array of strings.&quot;</span><span class="p">)</span>
            <span class="n">variables</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">evidence</span><span class="p">)</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="nb">len</span><span class="p">(</span><span class="n">evidence_card</span><span class="p">)</span> <span class="o">==</span> <span class="nb">len</span><span class="p">(</span><span class="n">evidence</span><span class="p">):</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Length of evidence_card doesn&#39;t match length of evidence&quot;</span><span class="p">)</span>

        <span class="n">values</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">values</span><span class="o">.</span><span class="n">ndim</span> <span class="o">!=</span> <span class="mi">2</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s2">&quot;Values must be a 2D list/array&quot;</span><span class="p">)</span>

        <span class="nb">super</span><span class="p">(</span><span class="n">TabularCPD</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="n">variables</span><span class="p">,</span> <span class="n">cardinality</span><span class="p">,</span> <span class="n">values</span><span class="o">.</span><span class="n">flatten</span><span class="p">(</span><span class="s1">&#39;C&#39;</span><span class="p">),</span>
                                         <span class="n">state_names</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">state_names</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">var_str</span> <span class="o">=</span> <span class="s1">&#39;&lt;TabularCPD representing P(</span><span class="si">{var}</span><span class="s1">:</span><span class="si">{card}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
            <span class="n">var</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">variable</span><span class="p">,</span> <span class="n">card</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">variable_card</span><span class="p">)</span>

        <span class="n">evidence</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
        <span class="n">evidence_card</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cardinality</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
        <span class="k">if</span> <span class="n">evidence</span><span class="p">:</span>
            <span class="n">evidence_str</span> <span class="o">=</span> <span class="s1">&#39; | &#39;</span> <span class="o">+</span> <span class="s1">&#39;, &#39;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="s1">&#39;</span><span class="si">{var}</span><span class="s1">:</span><span class="si">{card}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">var</span><span class="o">=</span><span class="n">var</span><span class="p">,</span> <span class="n">card</span><span class="o">=</span><span class="n">card</span><span class="p">)</span>
                                              <span class="k">for</span> <span class="n">var</span><span class="p">,</span> <span class="n">card</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">evidence</span><span class="p">,</span> <span class="n">evidence_card</span><span class="p">)])</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">evidence_str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>

        <span class="k">return</span> <span class="n">var_str</span> <span class="o">+</span> <span class="n">evidence_str</span> <span class="o">+</span> <span class="s1">&#39;) at </span><span class="si">{address}</span><span class="s1">&gt;&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">address</span><span class="o">=</span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="bp">self</span><span class="p">)))</span>

<div class="viewcode-block" id="TabularCPD.get_values"><a class="viewcode-back" href="../../../../factors.html#pgmpy.factors.discrete.CPD.TabularCPD.get_values">[docs]</a>    <span class="k">def</span> <span class="nf">get_values</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns the cpd</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.factors.discrete import TabularCPD</span>
<span class="sd">        &gt;&gt;&gt; cpd = TabularCPD(&#39;grade&#39;, 3, [[0.1, 0.1],</span>
<span class="sd">        ...                               [0.1, 0.1],</span>
<span class="sd">        ...                               [0.8, 0.8]],</span>
<span class="sd">        ...                  evidence=&#39;evi1&#39;, evidence_card=2)</span>
<span class="sd">        &gt;&gt;&gt; cpd.get_values()</span>
<span class="sd">        array([[ 0.1,  0.1],</span>
<span class="sd">               [ 0.1,  0.1],</span>
<span class="sd">               [ 0.8,  0.8]])</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">variable</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">cardinality</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">np</span><span class="o">.</span><span class="n">prod</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">cardinality</span><span class="p">[</span><span class="mi">1</span><span class="p">:]))</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">prod</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">cardinality</span><span class="p">))</span></div>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_make_table_str</span><span class="p">(</span><span class="n">tablefmt</span><span class="o">=</span><span class="s2">&quot;grid&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_str</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">phi_or_p</span><span class="o">=</span><span class="s2">&quot;p&quot;</span><span class="p">,</span> <span class="n">tablefmt</span><span class="o">=</span><span class="s2">&quot;fancy_grid&quot;</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">TabularCPD</span><span class="p">)</span><span class="o">.</span><span class="n">_str</span><span class="p">(</span><span class="n">phi_or_p</span><span class="p">,</span> <span class="n">tablefmt</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_make_table_str</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tablefmt</span><span class="o">=</span><span class="s2">&quot;fancy_grid&quot;</span><span class="p">,</span> <span class="n">print_state_names</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
        <span class="n">headers_list</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="c1"># build column headers</span>

        <span class="n">evidence</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
        <span class="n">evidence_card</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cardinality</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
        <span class="k">if</span> <span class="n">evidence</span><span class="p">:</span>
            <span class="n">col_indexes</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">product</span><span class="p">(</span><span class="o">*</span><span class="p">[</span><span class="nb">range</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">evidence_card</span><span class="p">])))</span>
            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">state_names</span> <span class="ow">and</span> <span class="n">print_state_names</span><span class="p">:</span>
                <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">evidence_card</span><span class="p">)):</span>
                    <span class="n">column_header</span> <span class="o">=</span> <span class="p">[</span><span class="nb">str</span><span class="p">(</span><span class="n">evidence</span><span class="p">[</span><span class="n">i</span><span class="p">])]</span> <span class="o">+</span> <span class="p">[</span><span class="s1">&#39;</span><span class="si">{var}</span><span class="s1">(</span><span class="si">{state}</span><span class="s1">)&#39;</span><span class="o">.</span><span class="n">format</span>
                                                     <span class="p">(</span><span class="n">var</span><span class="o">=</span><span class="n">evidence</span><span class="p">[</span><span class="n">i</span><span class="p">],</span>
                                                      <span class="n">state</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">state_names</span><span class="p">[</span><span class="n">evidence</span><span class="p">[</span><span class="n">i</span><span class="p">]][</span><span class="n">d</span><span class="p">])</span>
                                                     <span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">col_indexes</span><span class="o">.</span><span class="n">T</span><span class="p">[</span><span class="n">i</span><span class="p">]]</span>
                    <span class="n">headers_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">column_header</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">evidence_card</span><span class="p">)):</span>
                    <span class="n">column_header</span> <span class="o">=</span> <span class="p">[</span><span class="nb">str</span><span class="p">(</span><span class="n">evidence</span><span class="p">[</span><span class="n">i</span><span class="p">])]</span> <span class="o">+</span> <span class="p">[</span><span class="s1">&#39;</span><span class="si">{s}</span><span class="s1">_</span><span class="si">{d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">s</span><span class="o">=</span><span class="n">evidence</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="n">d</span><span class="o">=</span><span class="n">d</span><span class="p">)</span> <span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">col_indexes</span><span class="o">.</span><span class="n">T</span><span class="p">[</span><span class="n">i</span><span class="p">]]</span>
                    <span class="n">headers_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">column_header</span><span class="p">)</span>

        <span class="c1"># Build row headers</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">state_names</span> <span class="ow">and</span> <span class="n">print_state_names</span><span class="p">:</span>
            <span class="n">variable_array</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;</span><span class="si">{var}</span><span class="s1">(</span><span class="si">{state}</span><span class="s1">)&#39;</span><span class="o">.</span><span class="n">format</span>
                               <span class="p">(</span><span class="n">var</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">variable</span><span class="p">,</span> <span class="n">state</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">state_names</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">variable</span><span class="p">][</span><span class="n">i</span><span class="p">])</span>
                               <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">variable_card</span><span class="p">)]]</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">variable_array</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;</span><span class="si">{s}</span><span class="s1">_</span><span class="si">{d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">s</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">variable</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">variable_card</span><span class="p">)]]</span>
        <span class="c1"># Stack with data</span>
        <span class="n">labeled_rows</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">hstack</span><span class="p">((</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">variable_array</span><span class="p">)</span><span class="o">.</span><span class="n">T</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_values</span><span class="p">()))</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
        <span class="c1"># No support for multi-headers in tabulate</span>
        <span class="n">cdf_str</span> <span class="o">=</span> <span class="n">tabulate</span><span class="p">(</span><span class="n">headers_list</span> <span class="o">+</span> <span class="n">labeled_rows</span><span class="p">,</span> <span class="n">tablefmt</span><span class="o">=</span><span class="n">tablefmt</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">cdf_str</span>

<div class="viewcode-block" id="TabularCPD.copy"><a class="viewcode-back" href="../../../../factors.html#pgmpy.factors.discrete.CPD.TabularCPD.copy">[docs]</a>    <span class="k">def</span> <span class="nf">copy</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a copy of the TabularCPD object.</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.factors.discrete import TabularCPD</span>
<span class="sd">        &gt;&gt;&gt; cpd = TabularCPD(&#39;grade&#39;, 2,</span>
<span class="sd">        ...                  [[0.7, 0.6, 0.6, 0.2],[0.3, 0.4, 0.4, 0.8]],</span>
<span class="sd">        ...                  [&#39;intel&#39;, &#39;diff&#39;], [2, 2])</span>
<span class="sd">        &gt;&gt;&gt; copy = cpd.copy()</span>
<span class="sd">        &gt;&gt;&gt; copy.variable</span>
<span class="sd">        &#39;grade&#39;</span>
<span class="sd">        &gt;&gt;&gt; copy.variable_card</span>
<span class="sd">        2</span>
<span class="sd">        &gt;&gt;&gt; copy.evidence</span>
<span class="sd">        [&#39;intel&#39;, &#39;diff&#39;]</span>
<span class="sd">        &gt;&gt;&gt; copy.values</span>
<span class="sd">        array([[[ 0.7,  0.6],</span>
<span class="sd">                [ 0.6,  0.2]],</span>

<span class="sd">               [[ 0.3,  0.4],</span>
<span class="sd">                [ 0.4,  0.8]]])</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">evidence</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span> <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1</span> <span class="k">else</span> <span class="kc">None</span>
        <span class="n">evidence_card</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cardinality</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span> <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1</span> <span class="k">else</span> <span class="kc">None</span>
        <span class="k">return</span> <span class="n">TabularCPD</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">variable</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">variable_card</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_values</span><span class="p">(),</span>
                          <span class="n">evidence</span><span class="p">,</span> <span class="n">evidence_card</span><span class="p">)</span></div>

<div class="viewcode-block" id="TabularCPD.normalize"><a class="viewcode-back" href="../../../../factors.html#pgmpy.factors.discrete.CPD.TabularCPD.normalize">[docs]</a>    <span class="k">def</span> <span class="nf">normalize</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">inplace</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Normalizes the cpd table.</span>

<span class="sd">        Parameters</span>
<span class="sd">        ----------</span>
<span class="sd">        inplace: boolean</span>
<span class="sd">            If inplace=True it will modify the CPD itself, else would return</span>
<span class="sd">            a new CPD</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.factors.discrete import TabularCPD</span>
<span class="sd">        &gt;&gt;&gt; cpd_table = TabularCPD(&#39;grade&#39;, 2,</span>
<span class="sd">        ...                        [[0.7, 0.2, 0.6, 0.2],[0.4, 0.4, 0.4, 0.8]],</span>
<span class="sd">        ...                        [&#39;intel&#39;, &#39;diff&#39;], [2, 2])</span>
<span class="sd">        &gt;&gt;&gt; cpd_table.normalize()</span>
<span class="sd">        &gt;&gt;&gt; cpd_table.get_values()</span>
<span class="sd">        array([[ 0.63636364,  0.33333333,  0.6       ,  0.2       ],</span>
<span class="sd">               [ 0.36363636,  0.66666667,  0.4       ,  0.8       ]])</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">tabular_cpd</span> <span class="o">=</span> <span class="bp">self</span> <span class="k">if</span> <span class="n">inplace</span> <span class="k">else</span> <span class="bp">self</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
        <span class="n">cpd</span> <span class="o">=</span> <span class="n">tabular_cpd</span><span class="o">.</span><span class="n">get_values</span><span class="p">()</span>
        <span class="n">tabular_cpd</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="p">(</span><span class="n">cpd</span> <span class="o">/</span> <span class="n">cpd</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">))</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="n">tabular_cpd</span><span class="o">.</span><span class="n">cardinality</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">inplace</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">tabular_cpd</span></div>

<div class="viewcode-block" id="TabularCPD.marginalize"><a class="viewcode-back" href="../../../../factors.html#pgmpy.factors.discrete.CPD.TabularCPD.marginalize">[docs]</a>    <span class="k">def</span> <span class="nf">marginalize</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">variables</span><span class="p">,</span> <span class="n">inplace</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Modifies the cpd table with marginalized values.</span>

<span class="sd">        Parameters</span>
<span class="sd">        ----------</span>
<span class="sd">        variables: list, array-like</span>
<span class="sd">            list of variable to be marginalized</span>

<span class="sd">        inplace: boolean</span>
<span class="sd">            If inplace=True it will modify the CPD itself, else would return</span>
<span class="sd">            a new CPD</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.factors.discrete import TabularCPD</span>
<span class="sd">        &gt;&gt;&gt; cpd_table = TabularCPD(&#39;grade&#39;, 2,</span>
<span class="sd">        ...                        [[0.7, 0.6, 0.6, 0.2],[0.3, 0.4, 0.4, 0.8]],</span>
<span class="sd">        ...                        [&#39;intel&#39;, &#39;diff&#39;], [2, 2])</span>
<span class="sd">        &gt;&gt;&gt; cpd_table.marginalize([&#39;diff&#39;])</span>
<span class="sd">        &gt;&gt;&gt; cpd_table.get_values()</span>
<span class="sd">        array([[ 0.65,  0.4 ],</span>
<span class="sd">                [ 0.35,  0.6 ]])</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">variable</span> <span class="ow">in</span> <span class="n">variables</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Marginalization not allowed on the variable on which CPD is defined&quot;</span><span class="p">)</span>

        <span class="n">tabular_cpd</span> <span class="o">=</span> <span class="bp">self</span> <span class="k">if</span> <span class="n">inplace</span> <span class="k">else</span> <span class="bp">self</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>

        <span class="nb">super</span><span class="p">(</span><span class="n">TabularCPD</span><span class="p">,</span> <span class="n">tabular_cpd</span><span class="p">)</span><span class="o">.</span><span class="n">marginalize</span><span class="p">(</span><span class="n">variables</span><span class="p">)</span>
        <span class="n">tabular_cpd</span><span class="o">.</span><span class="n">normalize</span><span class="p">()</span>

        <span class="k">if</span> <span class="ow">not</span> <span class="n">inplace</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">tabular_cpd</span></div>

    <span class="nd">@StateNameDecorator</span><span class="p">(</span><span class="n">argument</span><span class="o">=</span><span class="s1">&#39;values&#39;</span><span class="p">,</span> <span class="n">return_val</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
<div class="viewcode-block" id="TabularCPD.reduce"><a class="viewcode-back" href="../../../../factors.html#pgmpy.factors.discrete.CPD.TabularCPD.reduce">[docs]</a>    <span class="k">def</span> <span class="nf">reduce</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">values</span><span class="p">,</span> <span class="n">inplace</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Reduces the cpd table to the context of given variable values.</span>

<span class="sd">        Parameters</span>
<span class="sd">        ----------</span>
<span class="sd">        values: list, array-like</span>
<span class="sd">            A list of tuples of the form (variable_name, variable_state).</span>

<span class="sd">        inplace: boolean</span>
<span class="sd">            If inplace=True it will modify the factor itself, else would return</span>
<span class="sd">            a new factor.</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.factors.discrete import TabularCPD</span>
<span class="sd">        &gt;&gt;&gt; cpd_table = TabularCPD(&#39;grade&#39;, 2,</span>
<span class="sd">        ...                        [[0.7, 0.6, 0.6, 0.2],[0.3, 0.4, 0.4, 0.8]],</span>
<span class="sd">        ...                        [&#39;intel&#39;, &#39;diff&#39;], [2, 2])</span>
<span class="sd">        &gt;&gt;&gt; cpd_table.reduce([(&#39;diff&#39;, 0)])</span>
<span class="sd">        &gt;&gt;&gt; cpd_table.get_values()</span>
<span class="sd">        array([[ 0.7,  0.6],</span>
<span class="sd">               [ 0.3,  0.4]])</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">variable</span> <span class="ow">in</span> <span class="p">(</span><span class="n">value</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">values</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Reduce not allowed on the variable on which CPD is defined&quot;</span><span class="p">)</span>

        <span class="n">tabular_cpd</span> <span class="o">=</span> <span class="bp">self</span> <span class="k">if</span> <span class="n">inplace</span> <span class="k">else</span> <span class="bp">self</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>

        <span class="nb">super</span><span class="p">(</span><span class="n">TabularCPD</span><span class="p">,</span> <span class="n">tabular_cpd</span><span class="p">)</span><span class="o">.</span><span class="n">reduce</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
        <span class="n">tabular_cpd</span><span class="o">.</span><span class="n">normalize</span><span class="p">()</span>

        <span class="k">if</span> <span class="ow">not</span> <span class="n">inplace</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">tabular_cpd</span></div>

<div class="viewcode-block" id="TabularCPD.to_factor"><a class="viewcode-back" href="../../../../factors.html#pgmpy.factors.discrete.CPD.TabularCPD.to_factor">[docs]</a>    <span class="k">def</span> <span class="nf">to_factor</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns an equivalent factor with the same variables, cardinality, values as that of the cpd</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.factors.discrete import TabularCPD</span>
<span class="sd">        &gt;&gt;&gt; cpd = TabularCPD(&#39;grade&#39;, 3, [[0.1, 0.1],</span>
<span class="sd">        ...                               [0.1, 0.1],</span>
<span class="sd">        ...                               [0.8, 0.8]],</span>
<span class="sd">        ...                  evidence=&#39;evi1&#39;, evidence_card=2)</span>
<span class="sd">        &gt;&gt;&gt; factor = cpd.to_factor()</span>
<span class="sd">        &gt;&gt;&gt; factor</span>
<span class="sd">        &lt;DiscreteFactor representing phi(grade:3, evi1:2) at 0x7f847a4f2d68&gt;</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">return</span> <span class="n">DiscreteFactor</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">cardinality</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">values</span><span class="p">)</span></div>

<div class="viewcode-block" id="TabularCPD.reorder_parents"><a class="viewcode-back" href="../../../../factors.html#pgmpy.factors.discrete.CPD.TabularCPD.reorder_parents">[docs]</a>    <span class="k">def</span> <span class="nf">reorder_parents</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">new_order</span><span class="p">,</span> <span class="n">inplace</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Returns a new cpd table according to provided order.</span>

<span class="sd">        Parameters</span>
<span class="sd">        ----------</span>
<span class="sd">        new_order: list</span>
<span class="sd">            list of new ordering of variables</span>

<span class="sd">        inplace: boolean</span>
<span class="sd">            If inplace == True it will modify the CPD itself</span>
<span class="sd">            otherwise new value will be returned without affecting old values</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        Consider a CPD P(grade| diff, intel)</span>
<span class="sd">        &gt;&gt;&gt; cpd = TabularCPD(&#39;grade&#39;,3,[[0.1,0.1,0.1,0.1,0.1,0.1],</span>
<span class="sd">                                        [0.1,0.1,0.1,0.1,0.1,0.1],</span>
<span class="sd">                                        [0.8,0.8,0.8,0.8,0.8,0.8]],</span>
<span class="sd">                                    evidence=[&#39;diff&#39;, &#39;intel&#39;], evidence_card=[2,3])</span>
<span class="sd">        &gt;&gt;&gt; print(cpd)</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        | diff    | diff_0  | diff_0  | diff_0  | diff_1  | diff_1  | diff_1  |</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        | intel   | intel_0 | intel_1 | intel_2 | intel_0 | intel_1 | intel_2 |</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        | grade_0 | 0.1     | 0.1     | 0.1     | 0.1     | 0.1     | 0.1     |</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        | grade_1 | 0.1     | 0.1     | 0.1     | 0.1     | 0.1     | 0.1     |</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        | grade_2 | 0.8     | 0.8     | 0.8     | 0.8     | 0.8     | 0.8     |</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        &gt;&gt;&gt; cpd.values</span>
<span class="sd">        array([[[ 0.1,  0.1,  0.1],</span>
<span class="sd">                [ 0.1,  0.1,  0.1]],</span>

<span class="sd">               [[ 0.1,  0.1,  0.1],</span>
<span class="sd">                [ 0.1,  0.1,  0.1]],</span>

<span class="sd">               [[ 0.8,  0.8,  0.8],</span>
<span class="sd">                [ 0.8,  0.8,  0.8]]])</span>
<span class="sd">        &gt;&gt;&gt; cpd.variables</span>
<span class="sd">        [&#39;grade&#39;, &#39;diff&#39;, &#39;intel&#39;]</span>
<span class="sd">        &gt;&gt;&gt; cpd.cardinality</span>
<span class="sd">        array([3, 2, 3])</span>
<span class="sd">        &gt;&gt;&gt; cpd.variable</span>
<span class="sd">        &#39;grade&#39;</span>
<span class="sd">        &gt;&gt;&gt; cpd.variable_card</span>
<span class="sd">        3</span>

<span class="sd">        &gt;&gt;&gt; cpd.reorder_parents([&#39;intel&#39;, &#39;diff&#39;])</span>
<span class="sd">        array([[ 0.1,  0.1,  0.2,  0.2,  0.1,  0.1],</span>
<span class="sd">               [ 0.1,  0.1,  0.1,  0.1,  0.1,  0.1],</span>
<span class="sd">               [ 0.8,  0.8,  0.7,  0.7,  0.8,  0.8]])</span>
<span class="sd">        &gt;&gt;&gt; print(cpd)</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        | intel   | intel_0 | intel_0 | intel_1 | intel_1 | intel_2 | intel_2 |</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        | diff    | diff_0  | diff_1  | diff_0  | diff_1  | diff_0  | diff_1  |</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        | grade_0 | 0.1     | 0.1     | 0.2     | 0.2     | 0.1     | 0.1     |</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        | grade_1 | 0.1     | 0.1     | 0.1     | 0.1     | 0.1     | 0.1     |</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>
<span class="sd">        | grade_2 | 0.8     | 0.8     | 0.7     | 0.7     | 0.8     | 0.8     |</span>
<span class="sd">        +---------+---------+---------+---------+---------+---------+---------+</span>

<span class="sd">        &gt;&gt;&gt; cpd.values</span>
<span class="sd">        array([[[ 0.1,  0.1],</span>
<span class="sd">                [ 0.2,  0.2],</span>
<span class="sd">                [ 0.1,  0.1]],</span>

<span class="sd">               [[ 0.1,  0.1],</span>
<span class="sd">                [ 0.1,  0.1],</span>
<span class="sd">                [ 0.1,  0.1]],</span>

<span class="sd">               [[ 0.8,  0.8],</span>
<span class="sd">                [ 0.7,  0.7],</span>
<span class="sd">                [ 0.8,  0.8]]])</span>

<span class="sd">        &gt;&gt;&gt; cpd.variables</span>
<span class="sd">        [&#39;grade&#39;, &#39;intel&#39;, &#39;diff&#39;]</span>
<span class="sd">        &gt;&gt;&gt; cpd.cardinality</span>
<span class="sd">        array([3, 3, 2])</span>
<span class="sd">        &gt;&gt;&gt; cpd.variable</span>
<span class="sd">        &#39;grade&#39;</span>
<span class="sd">        &gt;&gt;&gt; cpd.variable_card</span>
<span class="sd">        3</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">)</span> <span class="o">&lt;=</span> <span class="mi">1</span> <span class="ow">or</span> <span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="n">new_order</span><span class="p">)</span> <span class="o">-</span> <span class="nb">set</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">))</span> <span class="ow">or</span>
                <span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">[</span><span class="mi">1</span><span class="p">:])</span> <span class="o">-</span> <span class="nb">set</span><span class="p">(</span><span class="n">new_order</span><span class="p">))):</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;New order either has missing or extra arguments&quot;</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">new_order</span> <span class="o">!=</span> <span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">[</span><span class="mi">1</span><span class="p">:]:</span>
                <span class="n">evidence</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
                <span class="n">evidence_card</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cardinality</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
                <span class="n">card_map</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">evidence</span><span class="p">,</span> <span class="n">evidence_card</span><span class="p">))</span>
                <span class="n">old_pos_map</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">evidence</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">evidence</span><span class="p">))))</span>
                <span class="n">trans_ord</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="p">[(</span><span class="n">old_pos_map</span><span class="p">[</span><span class="n">letter</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="k">for</span> <span class="n">letter</span> <span class="ow">in</span> <span class="n">new_order</span><span class="p">]</span>
                <span class="n">new_values</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">values</span><span class="p">,</span> <span class="n">trans_ord</span><span class="p">)</span>

                <span class="k">if</span> <span class="n">inplace</span><span class="p">:</span>
                    <span class="n">variables</span> <span class="o">=</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">[</span><span class="mi">0</span><span class="p">]]</span> <span class="o">+</span> <span class="n">new_order</span>
                    <span class="n">cardinality</span> <span class="o">=</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">variable_card</span><span class="p">]</span> <span class="o">+</span> <span class="p">[</span><span class="n">card_map</span><span class="p">[</span><span class="n">var</span><span class="p">]</span> <span class="k">for</span> <span class="n">var</span> <span class="ow">in</span> <span class="n">new_order</span><span class="p">]</span>
                    <span class="nb">super</span><span class="p">(</span><span class="n">TabularCPD</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="n">variables</span><span class="p">,</span> <span class="n">cardinality</span><span class="p">,</span> <span class="n">new_values</span><span class="o">.</span><span class="n">flatten</span><span class="p">(</span><span class="s1">&#39;C&#39;</span><span class="p">))</span>
                    <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_values</span><span class="p">()</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="k">return</span> <span class="n">new_values</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">cardinality</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">np</span><span class="o">.</span><span class="n">prod</span><span class="p">([</span><span class="n">card_map</span><span class="p">[</span><span class="n">var</span><span class="p">]</span> <span class="k">for</span> <span class="n">var</span> <span class="ow">in</span> <span class="n">new_order</span><span class="p">]))</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">warn</span><span class="p">(</span><span class="s2">&quot;Same ordering provided as current&quot;</span><span class="p">)</span>
                <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_values</span><span class="p">()</span></div>

    <span class="k">def</span> <span class="nf">get_evidence</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">variables</span><span class="p">[:</span><span class="mi">0</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span></div>

<span class="c1"># Commenting out because not used anywhere for now and not implemented in a very good way.</span>
<span class="c1"># class TreeCPD(nx.DiGraph):</span>
<span class="c1">#     &quot;&quot;&quot;</span>
<span class="c1">#     Base Class for Tree CPD.</span>
<span class="c1">#     &quot;&quot;&quot;</span>
<span class="c1">#     def __init__(self, data=None):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Base Class for Tree CPD.</span>
<span class="c1">#</span>
<span class="c1">#         Parameters</span>
<span class="c1">#         ----------</span>
<span class="c1">#         data: input tree</span>
<span class="c1">#             Data to initialize the tree. If data=None (default) an empty</span>
<span class="c1">#             tree is created. The data can be an edge list with label for</span>
<span class="c1">#             each edge. Label should be the observed value of the variable.</span>
<span class="c1">#</span>
<span class="c1">#         Examples</span>
<span class="c1">#         --------</span>
<span class="c1">#         For P(A|B, C, D), to construct a tree like:</span>
<span class="c1">#</span>
<span class="c1">#                     B</span>
<span class="c1">#              0 /        \1</span>
<span class="c1">#               /          \</span>
<span class="c1">#         P(A|b_0)          C</span>
<span class="c1">#                    0/         \1</span>
<span class="c1">#                    /           \</span>
<span class="c1">#             P(A|b_1, c_0)      D</span>
<span class="c1">#                           0/       \</span>
<span class="c1">#                           /         \</span>
<span class="c1">#             P(A|b_1,c_1,d_0)      P(A|b_1,c_1,d_1)</span>
<span class="c1">#</span>
<span class="c1">#         &gt;&gt;&gt; from pgmpy.factors import TreeCPD, DiscreteFactor</span>
<span class="c1">#         &gt;&gt;&gt; tree = TreeCPD([(&#39;B&#39;, DiscreteFactor([&#39;A&#39;], [2], [0.8, 0.2]), &#39;0&#39;),</span>
<span class="c1">#         ...                 (&#39;B&#39;, &#39;C&#39;, &#39;1&#39;),</span>
<span class="c1">#         ...                 (&#39;C&#39;, DiscreteFactor([&#39;A&#39;], [2], [0.1, 0.9]), &#39;0&#39;),</span>
<span class="c1">#         ...                 (&#39;C&#39;, &#39;D&#39;, &#39;1&#39;),</span>
<span class="c1">#         ...                 (&#39;D&#39;, DiscreteFactor([&#39;A&#39;], [2], [0.9, 0.1]), &#39;0&#39;),</span>
<span class="c1">#         ...                 (&#39;D&#39;, DiscreteFactor([&#39;A&#39;], [2], [0.4, 0.6]), &#39;1&#39;)])</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         nx.DiGraph.__init__(self)</span>
<span class="c1">#         # TODO: Check cycles and self loops.</span>
<span class="c1">#         if data:</span>
<span class="c1">#             for edge in data:</span>
<span class="c1">#                 if len(edge) != 3:</span>
<span class="c1">#                     raise ValueError(&quot;Each edge tuple must have 3 values (u, v, label).&quot;)</span>
<span class="c1">#                 self.add_edge(edge[0], edge[1], label=edge[2])</span>
<span class="c1">#</span>
<span class="c1">#     def add_edge(self, u, v, label):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Add an edge between u and v.</span>
<span class="c1">#</span>
<span class="c1">#         The nodes u and v will be automatically added if they are</span>
<span class="c1">#         not already in the graph.</span>
<span class="c1">#</span>
<span class="c1">#         Parameters</span>
<span class="c1">#         ----------</span>
<span class="c1">#         u,v: nodes</span>
<span class="c1">#             Nodes can be any hashable (and not None) Python object.</span>
<span class="c1">#         label: string</span>
<span class="c1">#             Label should be value of the variable observed.</span>
<span class="c1">#             (underscore separated if multiple variables)</span>
<span class="c1">#         attr_dict: dictionary, optional (default= no attributes)</span>
<span class="c1">#             Dictionary of edge attributes. Key/Value pairs will</span>
<span class="c1">#             update existing data associated with the edge.</span>
<span class="c1">#         attr: Keyword arguments, optional</span>
<span class="c1">#             Edge data can be assigned using keyword arguments.</span>
<span class="c1">#</span>
<span class="c1">#         Examples</span>
<span class="c1">#         --------</span>
<span class="c1">#         &gt;&gt;&gt; from pgmpy.factors import TreeCPD, DiscreteFactor</span>
<span class="c1">#         &gt;&gt;&gt; tree = TreeCPD([(&#39;B&#39;, DiscreteFactor([&#39;A&#39;], [2], [0.8, 0.2]), 0),</span>
<span class="c1">#         ...                 (&#39;B&#39;, &#39;C&#39;, 1)])</span>
<span class="c1">#         &gt;&gt;&gt; tree.add_edge(&#39;C&#39;, DiscreteFactor([&#39;A&#39;], [2], [0.1, 0.9]), label=0)</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         if u != v:</span>
<span class="c1">#             if u in self.nodes() and v in self.nodes() and nx.has_path(self, v, u):</span>
<span class="c1">#                 # check if adding edge (u, v) forms a cycle</span>
<span class="c1">#                 raise ValueError(</span>
<span class="c1">#                     &#39;Loops are not allowed. Adding the edge from (%s-&gt;%s) forms a loop.&#39; % (u, v))</span>
<span class="c1">#             else:</span>
<span class="c1">#                 super(TreeCPD, self).add_edge(u, v, label=label)</span>
<span class="c1">#         else:</span>
<span class="c1">#             raise ValueError(&#39;Self loops are not allowed. Edge (%s-&gt;%s) forms a self loop.&#39; % (u, v))</span>
<span class="c1">#</span>
<span class="c1">#     def add_edges_from(self, ebunch):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Add all the edges in ebunch.</span>
<span class="c1">#</span>
<span class="c1">#         Parameters</span>
<span class="c1">#         ----------</span>
<span class="c1">#         ebunch : container of edges</span>
<span class="c1">#             Each edge given in the container will be added to the</span>
<span class="c1">#             graph. The edges must be given as as 3-tuples (u,v,label).</span>
<span class="c1">#         attr_dict : dictionary, optional (default= no attributes)</span>
<span class="c1">#             Dictionary of edge attributes.  Key/value pairs will</span>
<span class="c1">#             update existing data associated with each edge.</span>
<span class="c1">#         attr : keyword arguments, optional</span>
<span class="c1">#             Edge data (or labels or objects) can be assigned using</span>
<span class="c1">#             keyword arguments.</span>
<span class="c1">#</span>
<span class="c1">#         Examples</span>
<span class="c1">#         --------</span>
<span class="c1">#         &gt;&gt;&gt; from pgmpy.factors import TreeCPD, DiscreteFactor</span>
<span class="c1">#         &gt;&gt;&gt; tree = TreeCPD()</span>
<span class="c1">#         &gt;&gt;&gt; tree.add_edges_from([(&#39;B&#39;, &#39;C&#39;, 1), (&#39;C&#39;, &#39;D&#39;, 1),</span>
<span class="c1">#         ...                      (&#39;D&#39;, DiscreteFactor([&#39;A&#39;], [2], [0.6, 0.4]))])</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         for edge in ebunch:</span>
<span class="c1">#             if len(edge) == 2:</span>
<span class="c1">#                 raise ValueError(&quot;Each edge tuple must have 3 values (u, v, label).&quot;)</span>
<span class="c1">#         nx.DiGraph.add_edges_from(self, [(edge[0], edge[1], {&#39;label&#39;: edge[2]}) for edge in ebunch])</span>
<span class="c1">#</span>
<span class="c1">#     def to_tabular_cpd(self, parents_order=None):</span>
<span class="c1">#         edge_attributes = nx.get_edge_attributes(self, &#39;label&#39;)</span>
<span class="c1">#         edge_values = {}</span>
<span class="c1">#         edge_dict = {}</span>
<span class="c1">#         adjlist = {}</span>
<span class="c1">#         node_list = []</span>
<span class="c1">#         stack = []</span>
<span class="c1">#         values = []</span>
<span class="c1">#         cardinality = []</span>
<span class="c1">#</span>
<span class="c1">#         for edge in edge_attributes:</span>
<span class="c1">#             edge_dict.setdefault(edge[0], []).append(edge_attributes[edge])</span>
<span class="c1">#             if isinstance(edge[1], DiscreteFactor):</span>
<span class="c1">#                 variable = edge[1].scope()</span>
<span class="c1">#                 variable_card = edge[1].cardinality</span>
<span class="c1">#                 edge_values[(edge[0], edge[0] + edge_attributes.get(edge))] = edge[1].values.tolist()</span>
<span class="c1">#             else:</span>
<span class="c1">#                 edge_values[(edge[0], edge[0] + edge_attributes.get(edge))] = edge[1]</span>
<span class="c1">#         #adjlist</span>
<span class="c1">#         for source in self.nodes():</span>
<span class="c1">#             if not isinstance(source, DiscreteFactor):</span>
<span class="c1">#                 adjlist[source] = [i[1] for i in edge_attributes if not isinstance(i[1], DiscreteFactor) and i[0] == source]</span>
<span class="c1">#                 adjlist[source] = sorted(adjlist[source], key=lambda x: (len(nx.descendants(self, x)), x))</span>
<span class="c1">#</span>
<span class="c1">#         root = [node for node, in_degree in self.in_degree().items() if in_degree == 0][0]</span>
<span class="c1">#         stack.append(root)</span>
<span class="c1">#</span>
<span class="c1">#         #dfs</span>
<span class="c1">#         while stack:</span>
<span class="c1">#             top_node = stack[-1]</span>
<span class="c1">#             node_list.append(top_node)</span>
<span class="c1">#             stack = stack[:-1]</span>
<span class="c1">#             for end_node in adjlist[top_node]:</span>
<span class="c1">#                 stack.append(end_node)</span>
<span class="c1">#</span>
<span class="c1">#         for node in node_list:</span>
<span class="c1">#             cardinality.append(len(edge_dict[node]))</span>
<span class="c1">#</span>
<span class="c1">#         for i in product(*[range(index) for index in cardinality]):</span>
<span class="c1">#             edge_list = [a + str(b) for a, b in zip(node_list, i)]</span>
<span class="c1">#             current_node = root</span>
<span class="c1">#             for edge in edge_list:</span>
<span class="c1">#                 if (current_node, edge) in edge_values.keys():</span>
<span class="c1">#                     if not isinstance(edge_values[(current_node, edge)], list):</span>
<span class="c1">#                         current_node = edge_values[(current_node, edge)]</span>
<span class="c1">#                     else:</span>
<span class="c1">#                         values.append(edge_values[(current_node, edge)])</span>
<span class="c1">#                         break</span>
<span class="c1">#</span>
<span class="c1">#         values = np.array(values).flatten(&#39;F&#39;).reshape((len(values[0]), len(values)))</span>
<span class="c1">#         return TabularCPD(variable[0], int(variable_card[0]), values, node_list[::-1], cardinality)</span>
<span class="c1">#</span>
<span class="c1">#     def to_rule_cpd(self):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Returns a RuleCPD object which represents the TreeCPD</span>
<span class="c1">#</span>
<span class="c1">#         Examples</span>
<span class="c1">#         --------</span>
<span class="c1">#         &gt;&gt;&gt; from pgmpy.factors import TreeCPD, DiscreteFactor</span>
<span class="c1">#         &gt;&gt;&gt; tree = TreeCPD([(&#39;B&#39;, factors([&#39;A&#39;], [2], [0.8, 0.2]), &#39;0&#39;),</span>
<span class="c1">#         ...                 (&#39;B&#39;, &#39;C&#39;, &#39;1&#39;),</span>
<span class="c1">#         ...                 (&#39;C&#39;, factors([&#39;A&#39;], [2], [0.1, 0.9]), &#39;0&#39;),</span>
<span class="c1">#         ...                 (&#39;C&#39;, &#39;D&#39;, &#39;1&#39;),</span>
<span class="c1">#         ...                 (&#39;D&#39;, factors([&#39;A&#39;], [2], [0.9, 0.1]), &#39;0&#39;),</span>
<span class="c1">#         ...                 (&#39;D&#39;, factors([&#39;A&#39;], [2], [0.4, 0.6]), &#39;1&#39;)])</span>
<span class="c1">#         &gt;&gt;&gt; tree.to_rule_cpd()</span>
<span class="c1">#</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         # TODO: This method assumes that factors class has a get_variable method. Check this after merging navin&#39;s PR.</span>
<span class="c1">#         root = [node for node, in_degree in self.in_degree().items() if in_degree == 0][0]</span>
<span class="c1">#         paths_root_to_factors = {target: path for target, path in nx.single_source_shortest_path(self, root).items() if</span>
<span class="c1">#                                  isinstance(target, DiscreteFactor)}</span>
<span class="c1">#         for node in self.nodes_iter():</span>
<span class="c1">#             if isinstance(node, DiscreteFactor):</span>
<span class="c1">#                 rule_cpd = RuleCPD(node.scope()[0])</span>
<span class="c1">#</span>
<span class="c1">#         for factor, path in paths_root_to_factors.items():</span>
<span class="c1">#             rule_key = []</span>
<span class="c1">#             for node_index in range(len(path) - 1):</span>
<span class="c1">#                 rule_key.append(path[node_index] + &#39;_&#39; + self.edge[path[node_index]][path[node_index + 1]][&#39;label&#39;])</span>
<span class="c1">#             for value_index in range(len(factor.values)):</span>
<span class="c1">#                 rule_key.append(factor.get_variables()[0] + &#39;_&#39; + str(value_index))</span>
<span class="c1">#                 rule_cpd.add_rules({tuple(sorted(rule_key)): factor.values[value_index]})</span>
<span class="c1">#         return rule_cpd</span>
<span class="c1">#</span>
<span class="c1">#</span>
<span class="c1"># class RuleCPD:</span>
<span class="c1">#     def __init__(self, variable, rules=None):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Base class for Rule CPD.</span>
<span class="c1">#</span>
<span class="c1">#         Parameters</span>
<span class="c1">#         ----------</span>
<span class="c1">#         variable: str</span>
<span class="c1">#             The variable for which the CPD is to be defined.</span>
<span class="c1">#</span>
<span class="c1">#         rules: dict. (optional)</span>
<span class="c1">#             dict of rules. Each rule should be in the form of</span>
<span class="c1">#             tuple_of_assignment: probability.</span>
<span class="c1">#             For example: (&#39;A_0&#39;, &#39;J_0&#39;): 0.8</span>
<span class="c1">#</span>
<span class="c1">#         Examples</span>
<span class="c1">#         --------</span>
<span class="c1">#         For constructing a RuleCPD on variable A with the following rules:</span>
<span class="c1">#             p1: &lt;A_0, B_0; 0.8&gt;</span>
<span class="c1">#             p2: &lt;A_1, B_0; 0.2&gt;</span>
<span class="c1">#             p3: &lt;A_0, B_1, C_0; 0.4&gt;</span>
<span class="c1">#             p4: &lt;A_1, B_1, C_0; 0.6&gt;</span>
<span class="c1">#             p5: &lt;A_0, B_1, C_1; 0.9&gt;</span>
<span class="c1">#             p6: &lt;A_1, B_1, C_1; 0.1&gt;</span>
<span class="c1">#</span>
<span class="c1">#         &gt;&gt;&gt; from pgmpy.factors import RuleCPD</span>
<span class="c1">#         &gt;&gt;&gt; rule = RuleCPD(&#39;A&#39;, {(&#39;A_0&#39;, &#39;B_0&#39;): 0.8,</span>
<span class="c1">#         ...                      (&#39;A_1&#39;, &#39;B_0&#39;): 0.2,</span>
<span class="c1">#         ...                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_0&#39;): 0.4,</span>
<span class="c1">#         ...                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_0&#39;): 0.6,</span>
<span class="c1">#         ...                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_1&#39;): 0.9,</span>
<span class="c1">#         ...                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_1&#39;): 0.1})</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         self.variable = variable</span>
<span class="c1">#         if rules:</span>
<span class="c1">#             self.rules = {}</span>
<span class="c1">#             for rule, value in rules.items():</span>
<span class="c1">#                 self.rules[tuple(sorted(rule))] = value</span>
<span class="c1">#         else:</span>
<span class="c1">#             self.rules = {}</span>
<span class="c1">#         verify = self._verify()</span>
<span class="c1">#         if not verify[0]:</span>
<span class="c1">#             del self</span>
<span class="c1">#             raise ValueError(str(verify[1]) + &quot; and &quot; + str(verify[2]) + &quot; point to the same assignment&quot;)</span>
<span class="c1">#</span>
<span class="c1">#     def _verify(self):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Verifies the RuleCPD for multiple values of the</span>
<span class="c1">#         assignment.</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         from itertools import combinations</span>
<span class="c1">#         for rule, another_rule in combinations(self.rules, 2):</span>
<span class="c1">#             rule, another_rule = (rule, another_rule) if len(rule) &lt; len(another_rule) else (another_rule, rule)</span>
<span class="c1">#             if not set(rule) - set(another_rule):</span>
<span class="c1">#                 return False, rule, another_rule</span>
<span class="c1">#         return True,</span>
<span class="c1">#</span>
<span class="c1">#     def add_rules(self, rules):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Add one or more rules to the Rule CPD.</span>
<span class="c1">#</span>
<span class="c1">#         Parameters</span>
<span class="c1">#         ----------</span>
<span class="c1">#         rules: dict</span>
<span class="c1">#             dict of rules. Each rule should be in the form of</span>
<span class="c1">#             tuple_of_assignment: probability.</span>
<span class="c1">#             For example: (&#39;A_0&#39;, &#39;J_0&#39;): 0.8</span>
<span class="c1">#</span>
<span class="c1">#         Examples</span>
<span class="c1">#         --------</span>
<span class="c1">#         &gt;&gt;&gt; from pgmpy.factors import RuleCPD</span>
<span class="c1">#         &gt;&gt;&gt; rule = RuleCPD(variable=&#39;A&#39;)</span>
<span class="c1">#         &gt;&gt;&gt; rule.add_rules({(&#39;A_0&#39;, &#39;B_0&#39;): 0.8,</span>
<span class="c1">#         ...                 (&#39;A_1&#39;, &#39;B_0&#39;): 0.2})</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         for rule in rules:</span>
<span class="c1">#             self.rules[rule] = rules[rule]</span>
<span class="c1">#         verify = self._verify()</span>
<span class="c1">#         if not verify[0]:</span>
<span class="c1">#             for rule in rules:</span>
<span class="c1">#                 del(self.rules[rule])</span>
<span class="c1">#             raise ValueError(str(verify[1]) + &quot; and &quot; + str(verify[2]) + &quot; point to the same assignment&quot;)</span>
<span class="c1">#</span>
<span class="c1">#     def scope(self):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Returns a set of variables which is the scope of the Rule CPD.</span>
<span class="c1">#</span>
<span class="c1">#         Examples</span>
<span class="c1">#         --------</span>
<span class="c1">#         &gt;&gt;&gt; from pgmpy.factors import RuleCPD</span>
<span class="c1">#         &gt;&gt;&gt; rule = RuleCPD(&#39;A&#39;, {(&#39;A_0&#39;, &#39;B_0&#39;): 0.8,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_1&#39;, &#39;B_0&#39;): 0.2,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_0&#39;): 0.4,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_0&#39;): 0.6,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_!&#39;): 0.9,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_1&#39;): 0.1}</span>
<span class="c1">#         &gt;&gt;&gt; rule.scope()</span>
<span class="c1">#         {&#39;A&#39;, &#39;B&#39;, &#39;C&#39;}</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         scope = set()</span>
<span class="c1">#         for rule in self.rules:</span>
<span class="c1">#             scope.update([assignment.split(&#39;_&#39;)[0] for assignment in rule])</span>
<span class="c1">#         return scope</span>
<span class="c1">#</span>
<span class="c1">#     def cardinality(self, variable=None):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Returns a dict of variable: cardinality.</span>
<span class="c1">#</span>
<span class="c1">#         Parameters</span>
<span class="c1">#         ----------</span>
<span class="c1">#         variable: string, list</span>
<span class="c1">#             variable or list of variables whose cardinality will be returned.</span>
<span class="c1">#</span>
<span class="c1">#         Examples</span>
<span class="c1">#         --------</span>
<span class="c1">#         &gt;&gt;&gt; from pgmpy.factors import RuleCPD</span>
<span class="c1">#         &gt;&gt;&gt; rule = RuleCPD(&#39;A&#39;, {(&#39;A_0&#39;, &#39;B_0&#39;): 0.8,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_1&#39;, &#39;B_0&#39;): 0.2,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_0&#39;): 0.4,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_0&#39;): 0.6,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_!&#39;): 0.9,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_1&#39;): 0.1}</span>
<span class="c1">#         &gt;&gt;&gt; rule.cardinality()</span>
<span class="c1">#         {&#39;A&#39;: 2, &#39;B&#39;: 2, &#39;C&#39;: 2}</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         from itertools import chain</span>
<span class="c1">#         from collections import Counter</span>
<span class="c1">#         assignments = set(chain.from_iterable(self.rules))</span>
<span class="c1">#         cardinality = dict(Counter([element.split(&#39;_&#39;)[0] for element in assignments]))</span>
<span class="c1">#         if variable:</span>
<span class="c1">#             return cardinality[variable] if isinstance(variable, str) else {var: cardinality[var] for var in variable}</span>
<span class="c1">#         else:</span>
<span class="c1">#             return cardinality</span>
<span class="c1">#</span>
<span class="c1">#     def to_tabular_cpd(self, parents_order=None):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Returns an equivalent TabularCPD.</span>
<span class="c1">#</span>
<span class="c1">#         Parameters</span>
<span class="c1">#         ----------</span>
<span class="c1">#         parents_order: array-like. list, tuple. (optional)</span>
<span class="c1">#             The order of the evidence variables.</span>
<span class="c1">#</span>
<span class="c1">#         Examples</span>
<span class="c1">#         --------</span>
<span class="c1">#         &gt;&gt;&gt; from pgmpy.factors import RuleCPD</span>
<span class="c1">#         &gt;&gt;&gt; rule = RuleCPD(&#39;A&#39;, {(&#39;A_0&#39;, &#39;B_0&#39;): 0.8,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_1&#39;, &#39;B_0&#39;): 0.2,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_1&#39;): 0.9,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_1&#39;): 0.1,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_0&#39;): 0.4,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_0&#39;): 0.6,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_1&#39;): 0.3,</span>
<span class="c1">#         &gt;&gt;&gt;                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_1&#39;): 0.7})</span>
<span class="c1">#         &gt;&gt;&gt; rule.to_tabular_cpd()</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         if not parents_order:</span>
<span class="c1">#             parents_order = sorted(self.scope() - {self.variable})</span>
<span class="c1">#         cardinality_dict = self.cardinality()</span>
<span class="c1">#         cardinality_product = np.product(list(cardinality_dict.values()))</span>
<span class="c1">#         tabular_cpd = [[0] * cardinality_product</span>
<span class="c1">#                        for _ in range(cardinality_dict[self.variable])]</span>
<span class="c1">#         for rule, value in self.rules:</span>
<span class="c1">#             start, end = 0, cardinality_product</span>
<span class="c1">#             for var in sorted(rule):</span>
<span class="c1">#                 if var.split(&#39;_&#39;)[0] != self.variable:</span>
<span class="c1">#                     start, end = (start + (end-start)/cardinality_dict[var] * int(var.split(&#39;_&#39;)[1]),</span>
<span class="c1">#                                   start + (end-start)/cardinality_dict[var] * (int(var.split(&#39;_&#39;)[1]) + 1))</span>
<span class="c1">#                 else:</span>
<span class="c1">#                     var_assignment = int(var.split(&#39;_&#39;)[1])</span>
<span class="c1">#             for index in range(start, end):</span>
<span class="c1">#                 tabular_cpd[var_assignment][index] = value</span>
<span class="c1">#</span>
<span class="c1">#         return TabularCPD(self.variable, cardinality_dict[self.variable], tabular_cpd,</span>
<span class="c1">#                           parents_order, [cardinality_dict[var] for var in parents_order])</span>
<span class="c1">#</span>
<span class="c1">#     def _merge(self):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Removes the variable from the rules and then merges the rules</span>
<span class="c1">#         having the same variables.</span>
<span class="c1">#         For example:</span>
<span class="c1">#         If we are given these rules:</span>
<span class="c1">#         (&#39;A_0&#39;, &#39;B_0&#39;): 0.8,</span>
<span class="c1">#         (&#39;A_1&#39;, &#39;B_0&#39;): 0.2,</span>
<span class="c1">#         (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_1&#39;): 0.9,</span>
<span class="c1">#         (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_1&#39;): 0.1,</span>
<span class="c1">#         (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_0&#39;): 0.4,</span>
<span class="c1">#         (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_0&#39;): 0.6,</span>
<span class="c1">#         (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_1&#39;): 0.3,</span>
<span class="c1">#         (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_1&#39;): 0.7</span>
<span class="c1">#</span>
<span class="c1">#         then after merging _merge will return this dict:</span>
<span class="c1">#         {(&#39;B_0&#39;,): array([ 0.8,  0.2]),</span>
<span class="c1">#          (&#39;B_1&#39;, &#39;C_0&#39;, &#39;D_1&#39;): array([ 0.3,  0.7]),</span>
<span class="c1">#          (&#39;B_1&#39;, &#39;C_1&#39;): array([ 0.9,  0.1]),</span>
<span class="c1">#          (&#39;B_1&#39;, &#39;C_0&#39;, &#39;D_0&#39;): array([ 0.4,  0.6])}</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         var_card = self.cardinality(self.variable)</span>
<span class="c1">#         dict_without_var = {}</span>
<span class="c1">#         for assignments in self.rules.keys():</span>
<span class="c1">#             dict_without_var[tuple(sorted([var for var in assignments if not var.startswith(self.variable)]))] = None</span>
<span class="c1">#         for key in dict_without_var:</span>
<span class="c1">#             value_list = []</span>
<span class="c1">#             for assign in range(var_card):</span>
<span class="c1">#                 value_list.append(self.rules[tuple(sorted(list(key) + [(self.variable + &#39;_&#39; + str(assign))]))])</span>
<span class="c1">#             dict_without_var[key] = np.array(value_list)</span>
<span class="c1">#         return dict_without_var</span>
<span class="c1">#</span>
<span class="c1">#     def to_tree_cpd(self):</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         Return a TreeCPD object which represents the RuleCPD.</span>
<span class="c1">#</span>
<span class="c1">#         Examples</span>
<span class="c1">#         --------</span>
<span class="c1">#         &gt;&gt;&gt; from pgmpy.factors import RuleCPD</span>
<span class="c1">#         &gt;&gt;&gt; rule = RuleCPD(&#39;A&#39;, {(&#39;A_0&#39;, &#39;B_0&#39;): 0.8,</span>
<span class="c1">#         ...                      (&#39;A_1&#39;, &#39;B_0&#39;): 0.2,</span>
<span class="c1">#         ...                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_1&#39;): 0.9,</span>
<span class="c1">#         ...                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_1&#39;): 0.1,</span>
<span class="c1">#         ...                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_0&#39;): 0.4,</span>
<span class="c1">#         ...                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_0&#39;): 0.6,</span>
<span class="c1">#         ...                      (&#39;A_0&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_1&#39;): 0.3,</span>
<span class="c1">#         ...                      (&#39;A_1&#39;, &#39;B_1&#39;, &#39;C_0&#39;, &#39;D_1&#39;): 0.7})</span>
<span class="c1">#         &gt;&gt;&gt; rule.to_tree_cpd()</span>
<span class="c1">#         &lt;CPD.TreeCPD object at 0x7f6b6f952fd0&gt;</span>
<span class="c1">#         &quot;&quot;&quot;</span>
<span class="c1">#         from collections import OrderedDict</span>
<span class="c1">#         tree_cpd = TreeCPD()</span>
<span class="c1">#         merged_rules = OrderedDict(sorted(self._merge().items(), key=lambda t: len(t[0])))</span>
<span class="c1">#</span>
<span class="c1">#         for assignments, value in merged_rules.items():</span>
<span class="c1">#             for assignment_index in range(len(assignments) - 1):</span>
<span class="c1">#                 tree_cpd.add_edge(assignments[assignment_index].split(&#39;_&#39;)[0],</span>
<span class="c1">#                                   assignments[assignment_index+1].split(&#39;_&#39;)[0],</span>
<span class="c1">#                                   assignments[assignment_index].split(&#39;_&#39;)[1])</span>
<span class="c1">#             tree_cpd.add_edge(assignments[-1].split(&#39;_&#39;)[0],</span>
<span class="c1">#                               DiscreteFactor([self.variable], [len(value)], value),</span>
<span class="c1">#                               assignments[-1].split(&#39;_&#39;)[1])</span>
<span class="c1">#         return tree_cpd</span>
<span class="c1">#</span>
<span class="c1">#     def __str__(self):</span>
<span class="c1">#         from collections import OrderedDict</span>
<span class="c1">#         string = &quot;&quot;</span>
<span class="c1">#         for index, key in enumerate(OrderedDict(sorted(self.rules.items(), key=lambda t: len(t[0])))):</span>
<span class="c1">#             key_string = &#39;, &#39;.join(key)</span>
<span class="c1">#             string += &#39;p&#39; + str(index) + &#39;: &lt;&#39; + key_string + &#39;; &#39; + str(self.rules[key]) + &#39;&gt;&#39; + &#39;\n&#39;</span>
<span class="c1">#         return string</span>
</pre></div>

          </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../../../../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../../../../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="nav-item nav-item-0"><a href="../../../../index.html">pgmpy 0.1.2 documentation</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="../../../index.html" >Module code</a> &#187;</li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &#169; Copyright 2016, Ankur Ankan.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.5.1.
    </div>
  </body>
</html>